package com.groupseven.backend.controller;

import com.alibaba.fastjson.JSON;
import com.groupseven.backend.configuration.WebSocket.WebSocket;
import com.groupseven.backend.domain.Echarts.EchartsResult;
import com.groupseven.backend.domain.Echarts.EchartsWebSocket;
import com.groupseven.backend.domain.Program.Program;
import com.groupseven.backend.domain.Program.ProgramApplication;
import com.groupseven.backend.domain.ResultType;
import com.groupseven.backend.domain.User.User;
import com.groupseven.backend.services.EchartsService;
import com.groupseven.backend.services.ProgramService;
import com.groupseven.backend.services.UserService;
import com.groupseven.backend.test.DataEncode;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/api/v1/program")
public class ProgramController {
    @Autowired
    private ProgramService programService;
    @Autowired
    private UserService userService;
    @Autowired
    private EchartsService echartsService;
    @Autowired
    private WebSocket webSocket;
    @Autowired
    private DataEncode dataEncode;

    /**
     * 查看我的项目------教师功能
     * @Author 王志华
     * @param Username
     * @return
     * @throws AuthorizationException
     */
    //@RequiresPermissions("see_programs")
    @GetMapping( "/{Username}" )
    public ResultType showinfo(@PathVariable @Valid String Username) throws AuthorizationException{
//        Subject subject = SecurityUtils.getSubject();
//        subject.isPermitted("wssb");
//        System.out.println(Username);
           String username = dataEncode.encodeBae64(Username);
           User u1 = userService.selectByUsername(username);
           Program pro = new Program();
           pro.setManager(Username);
           List<Program> p1 = programService.selectByManager(pro);
           List<ProgramApplication> p2 = programService.getMyProgramApplications(Username);
           p2= programService.setManagerAndTeamMembers(p2);
            for(ProgramApplication i : p2){
                Program tmp = new Program();
                tmp.setProgramname(i.getProgramName());
                tmp.setAffiliation(i.getAffiliation());
                tmp.setApprovalStatus(i.getApprovalStatus());
                tmp.setManager(i.getManager().getName());
                tmp.setProgramNumber(i.getProgramNumber());
                tmp.setAmount(i.getReportExpenses());
                p1.add(tmp);
             }
//           for ( Program i : p1){
//               i.setProgramname(dataEncode.decodeBae64(i.getProgramname()));
//               i.setProgramNumber(dataEncode.decodeBae64(i.getProgramNumber()));
//               i.setPhone(dataEncode.decodeBae64(i.getPhone()));
//               i.setLevel(dataEncode.decodeBae64(i.getLevel()));
//           }
           return new ResultType(1,"查询成功！",200,null,null,p1,null,null);


    }

    /**
     * 查看全部项目------管理员功能
     * @Author 王志华
     * @return
     */
//    @NoRepeatSubmit
    @RequiresPermissions("program:view")
    @GetMapping( "/")
    public ResultType showAllInfo(){
        List<Program> p1 = programService.selectAllPrograms();
        List<ProgramApplication> p2 = programService.findAllProgamApplicationInfo();
        p2 = programService.setManagerAndTeamMembers(p2);
        for(ProgramApplication i : p2){
            Program tmp = new Program();
            tmp.setProgramname(i.getProgramName());
            tmp.setAffiliation(i.getAffiliation());
            tmp.setApprovalStatus(i.getApprovalStatus());
            tmp.setManager(i.getManager().getName());
            tmp.setProgramNumber(i.getProgramNumber());
            tmp.setAmount(i.getReportExpenses());
            p1.add(tmp);
        }
        return new ResultType(1,"查询成功！",200,null,null,p1,null,null);
    }


    /**
     * 修改项目
     * @Author 王志华
     * @param program
     * @return
     */
    @PutMapping("/")
    public ResultType change(@RequestBody  Program program){
        System.out.println(program.getProgramNumber());
        if(programService.modifyByProgramNumber(program)>0){
            return new ResultType(1,"修改成功！",200,null,null,null,null,null);
        }
        return new ResultType(0,"该项目不存在！修改失败！",200,null,null,null,null,null);
    }

    /**
     * 增添项目
     * @Author 王志华
     * @param program
     * @return
     */
    @RequiresPermissions("program:add")
    @PostMapping("/")
    public ResultType insertInfo(@RequestBody  Program program){
        System.out.println(program.getProgramname());
        System.out.println(program.getPhone());
        System.out.println(program.getLevel());
        program.setApprovalStatus(2);
        /////////////////////////////////////////////
        Date date=new Date();
        program.setStartTime(date);
        /////////////////////////////////////////////
        List<Program> tmp = new ArrayList<>();
        tmp.add(program);
        for (Program i : tmp){
            System.out.println(i.getProgramname());
        }
        if(programService.insertProgramInfo(program)>0) {
            EchartsResult result = new EchartsResult(1,"项目数量发生改变");
            result.setData(echartsService.getAffiliationAndQuantity());
            webSocket.sendAllMessage(JSON.toJSONString(result));
            return new ResultType(1, "插入成功！", 200, null, null, tmp, null,null);
        }
        return new ResultType(0, "该项目已存在！插入失败！", 200, null, null, null, null,null);
    }


    /**
     * 删除项目
     * @Author 王志华
     * @param deleteList
     * @return
     */
    @DeleteMapping("/s/{deleteList}")
    public ResultType deletePrograms(@PathVariable String[] deleteList){
        Map<String,Object> delete = new HashMap<>();
        delete.put("Programnumber",deleteList);
        if(programService.multipleDelete(delete)>0){
            EchartsWebSocket echartsWebSocket = new EchartsWebSocket();
            echartsWebSocket.setAffiliations(echartsService.getAffiliationAndQuantity());
            echartsWebSocket.setTeachers(echartsService.getTeachernaneAndQuantity());
            webSocket.sendOneMessage("admin",echartsWebSocket);
            return new ResultType(1,"删除成功！",200);
        }
        return new ResultType(0,"删除失败！",200);
    }

    @PostMapping("/s/")
    public ResultType deleteProgramsObject(@RequestBody List<Program> programs){
        List<String> deleteList = new ArrayList<>();
        for(Program iterator : programs){
            deleteList.add(iterator.getProgramNumber());
            System.out.println(iterator.getProgramNumber());
        }
        Map<String,Object> delete = new HashMap<>();
        delete.put("Programnumber",deleteList);
        if(programService.multipleDelete(delete)>0){
            EchartsWebSocket echartsWebSocket = new EchartsWebSocket();
            echartsWebSocket.setAffiliations(echartsService.getAffiliationAndQuantity());
            echartsWebSocket.setTeachers(echartsService.getTeachernaneAndQuantity());
            webSocket.sendOneMessage("admin",echartsWebSocket);
            return new ResultType(1,"删除成功！",200);
        }
        return new ResultType(0,"删除失败！",200);
    }

    /**
     * 删除项目
     * @Author 王志华
     * @param ProgramNumber
     * @return
     */
    @RequiresPermissions("program:delete")
    @DeleteMapping("/{ProgramNumber}")
    public ResultType deleteProgram(@PathVariable String ProgramNumber){
        if(programService.deleteByProgramNumber(ProgramNumber)>0){
            EchartsWebSocket echartsWebSocket = new EchartsWebSocket();
            echartsWebSocket.setAffiliations(echartsService.getAffiliationAndQuantity());
            echartsWebSocket.setTeachers(echartsService.getTeachernaneAndQuantity());
            webSocket.sendOneMessage("admin",echartsWebSocket);
            return new ResultType(1,"删除成功！",200);
        }
        return new ResultType(0,"删除失败！",200);
    }

    @GetMapping("/search/{query}")
    public ResultType searchPrograms(@PathVariable String query){
        List<Program> fuzzy = programService.FuzzySearch(query);
        ResultType result = new ResultType(1,"查询成功！",200);
        result.setPrograms(fuzzy);
        return result;
    }

    @GetMapping("/search/{username}/{query}")
    public ResultType searchMyPrograms(@PathVariable String username,@PathVariable String query){
        List<Program> fuzzy = programService.FuzzySearchMyPrograms(username,query);
        ResultType result = new ResultType(1,"查询成功！",200);
        result.setPrograms(fuzzy);
        return result;
    }
}
